﻿using Newtonsoft.Json;
using YukariToolBox.LightLog;

namespace CommonTools.Util;

/// <summary>
/// 工具类
/// </summary>
public class DiscordUtil
{
    public static readonly string PROMPT_PREFIX = "<#";

    public static readonly string PROMPT_SUFFIX = "#>";

    /// <summary>
    /// 生成唯一的 10 位字符串，作为任务 ID
    /// </summary>
    /// <returns></returns>
    public static string GenerateUniqueId()
    {
        return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10).ToUpper();
    }

    /// <summary>
    /// 拼接 Prompt 
    /// </summary>
    /// <param name="prompt"></param>
    /// <param name="picUrl"></param>
    /// <returns></returns>
    public static (string, string) Prompt(string prompt, string picUrl)
    {
        //形如: <#1234567890#>a cute cat
        string triggerId = GenerateUniqueId();
        if (!string.IsNullOrEmpty(picUrl) && prompt.StartsWith("http://") || prompt.StartsWith("https://"))
        {
            var splitResult = prompt.Split(' ');
            picUrl = splitResult[0];
            prompt = splitResult[1];
        }

        return (triggerId,
            $"{(string.IsNullOrWhiteSpace(picUrl) ? "" : $"{picUrl} ")}{PROMPT_PREFIX}{triggerId}{PROMPT_SUFFIX}{prompt}");
    }

    /// <summary>
    /// 友好的崩溃提示(x)
    /// </summary>
    public static void FriendlyException(UnhandledExceptionEventArgs args)
    {
        Exception e = args.ExceptionObject as Exception;

        if (e is JsonSerializationException)
            Log.Error("SuiFeng", "Json反序列化时出现错误");

        Log.UnhandledExceptionLog(args);
    }
}